using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Astro.Core;

public partial class astro_admin_people_Default : ControlPanelPage
{
	IAstroUser user = null;

	protected void Page_Load(object sender, EventArgs e)
	{
		LiHyperLink.SetNameToCompare(Context, "UserManagement");

		IAstroUser currentUser = AstroUsers.Current;


		if (Request.QueryString["user"] != null)
		{

			if (!IsPostBack)
			{
				user = AstroUsers.GetUser(Request.QueryString["user"]);


				if (user == null)
					throw new Exception("This user does not exist or cannot be edited.");

				if (!AstroUsers.IsAdmin(currentUser) && user.Name != currentUser.Name)
					throw new SecurityException("You do not have permission to edit this user");


				if (Request.QueryString["new"] != null && !IsPostBack)
				{
					Message.Text = "The user <strong>" + user.Name + "</strong> was created.";
					Message.Type = StatusType.Success;

                    Message1.Text = Message.Text;
                    Message1.Type = Message.Type;
				}
				PageText.Text = "Update " + user.ProperName + "'s profile.";
				AdminUserLinks.Visible = true;
				PasswordLink.NavigateUrl = string.Format("~/astro-admin/user-management/users/changepassword.aspx?user={0}", Request.QueryString["user"]);
				if (AstroUsers.CanRenameUsers && AstroUsers.IsAdmin(AstroUsers.Current))
				{
					AdminUserLinksDelim.Visible = true;
					RenameLink.Visible = true;
					RenameLink.NavigateUrl = string.Format("javascript:Telligent_Modal.Open('RenameUser.aspx?user={0}', 400, 200, null);", Request.QueryString["user"]);
				}
				txtExistingUserName.Text = Server.HtmlDecode(user.Name);
				txtProperName.Text = Server.HtmlDecode(user.ProperName);
				txtExistingEmail.Text = user.Email;
				txtAvatar.Text = user.Avatar;
				Editor.Text = user.Bio;
				txtWebsite.Text = string.IsNullOrEmpty(user.WebSite)
											 ? new Macros().FullUrl(new Urls().Home)
											 : Server.HtmlEncode(user.WebSite);

                Astro.Core.User cu = Astro.Core.User.FetchByColumn(Astro.Core.User.Columns.UniqueId, user.UniqueId);
                NameValueCollection nvcCustomFields = cu.CustomFields();
                CustomUserFormSettings cfs = CustomUserFormSettings.Get();
                if (cfs.HasFields)
                {
                    if (nvcCustomFields == null)
                    {
                        nvcCustomFields = new NameValueCollection();
                        foreach (CustomField cf in cfs.Fields)
                        {
                            if (Request.Form[cf.Id.ToString()] != null)
                                nvcCustomFields[cf.Name] = Request.Form[cf.Id.ToString()];
                        }
                    }

                    the_CustomFields.Text = cfs.GetHtmlForm(nvcCustomFields, false);
                }
                else
                {
                    CustomFieldsTab.Tab.Enabled = false;
                    the_CustomFields.Text = "";
                }

				bool isAdmin = AstroUsers.IsUserInRole(AstroUsers.Current.Name, AstroUsers.AdminRole);

				role_section.Visible = isAdmin;
				AllRoles.Visible = isAdmin;

				if (!isAdmin)
					Cancel_Edit.NavigateUrl = "~/astro-admin/";

				if (isAdmin)
				{
					RolePermissionsCollection rp = RolePermissionManager.GetRolePermissions();

					RolePermissionsCollection newrp = new RolePermissionsCollection();
					newrp.AddRange(rp);

					RolePermissions temp = newrp.Find(delegate(RolePermissions r)
																	{
																		return r.RoleName == AstroUsers.EveryoneRole;
																	});

					if (temp != null)
						newrp.Remove(temp);

					newrp.Sort(delegate(RolePermissions rp1, RolePermissions rp2)
					{
						return Comparer<string>.Default.Compare(rp1.RoleName, rp2.RoleName);
					});

					Roles.DataSource = newrp;
					Roles.DataBind();

					foreach (string role in user.Roles)
					{
						if (role == AstroUsers.AdminRole)
						{
							chkAdmin.Checked = true;

							if (AstroUsers.Current.Name == user.Name)
								chkAdmin.Enabled = false;
						}
					}
				}
			}

			new_user_container.Visible = false;
			User_List.Visible = false;
			user_edit_form.Visible = true;
		}
		else
		{

			if (!AstroUsers.IsUserInRole(currentUser.Name, AstroUsers.AdminRole))
				Response.Redirect("?user=" + currentUser.Name);

			new_user_container.Visible = true;
			user_edit_form.Visible = false;
			User_List.Visible = true;

			List<IAstroUser> users = AstroUsers.GetUsers("*");

			User_List.DataSource = users;
			User_List.DataBind();

			// filter out everyone if they are not a content publisher for licensing
			List<IAstroUser> filteredUsers = new List<IAstroUser>();
			filteredUsers.AddRange(users);

			bool isEveryonePublisher = RolePermissionManager.IsEveryoneAContentPublisher();

			if (!isEveryonePublisher)
			{
				foreach (IAstroUser user in users)
				{
					if (user.Roles != null && user.Roles[0] == AstroUsers.EveryoneRole)
						filteredUsers.Remove(user);
				}
			}
		}
	}

	protected void Roles_OnItemDataBound(object sender, DataListItemEventArgs e)
	{
		RolePermissions p = e.Item.DataItem as RolePermissions;

		if (p != null)
		{
			CheckBox role = e.Item.FindControl("role") as CheckBox;
			role.Text = p.RoleName;

			foreach (string rl in user.Roles)
			{
				if (rl.ToLower() == role.Text.ToLower())
					role.Checked = true;
			}
		}
	}

	protected void EditPerson_Click(object sender, EventArgs e)
	{
		try
		{
			IAstroUser currentUser = AstroUsers.Current;
			IAstroUser user = AstroUsers.GetUser(Request.QueryString["user"]);
			bool isAdmin = AstroUsers.IsAdmin(currentUser);

			if (!isAdmin && user.Name != currentUser.Name)
				throw new SecurityException("You do not have permission to edit this user");

			user.ProperName = Server.HtmlEncode(txtProperName.Text.Trim());
			user.Bio = Editor.Text.Trim();
			user.Email = txtExistingEmail.Text.Trim();

			if (!string.IsNullOrEmpty(txtWebsite.Text.Trim()))
				user.WebSite = Server.HtmlEncode(txtWebsite.Text.Trim());
			else
				user.WebSite = null;

			if (!string.IsNullOrEmpty(txtAvatar.Text.Trim()))
				user.Avatar = Server.HtmlEncode(txtAvatar.Text.Trim());
			else
				user.Avatar = null;

			if (isAdmin)
			{
				foreach (string role in user.Roles)
					AstroUsers.RemoveUserFromRole(user.Name, role);

				AstroUsers.AddUserToRole(user.Name, AstroUsers.EveryoneRole);

				if (chkAdmin.Checked == true)
					AstroUsers.AddUserToRole(user.Name, AstroUsers.AdminRole);

				foreach (DataListItem dli in Roles.Items)
				{
					CheckBox role = dli.FindControl("role") as CheckBox;

					if (role.Checked)
						AstroUsers.AddUserToRole(user.Name, role.Text);
				}
			}

            Astro.Core.User cu = Astro.Core.User.FetchByColumn(Astro.Core.User.Columns.UniqueId, user.UniqueId);
            CustomUserFormSettings cfs = CustomUserFormSettings.Get();
            if (cfs.HasFields)
            {
                foreach (CustomField cf in cfs.Fields)
                {
                    if (cf.FieldType == FieldType.CheckBox && Request.Form[cf.Id.ToString()] == null)
                        cu[cf.Name] = null; // false.ToString();
                    else if (cf.FieldType == FieldType.DateTime && Request.Form[cf.Id.ToString()].IndexOf("_") > -1)
                        cu[cf.Name] = null;
                    else
                        cu[cf.Name] = Request.Form[cf.Id.ToString()];
                }
            }

            AstroUsers.Save(user, AstroUsers.Current.Name);
            cu.Save();

			Message.Text = "The user <strong>" + user.ProperName + "</strong> was updated.";
			Message.Type = StatusType.Success;

            Message1.Text = Message.Text;
            Message1.Type = Message.Type;
		}
		catch (Exception ex)
		{
			string exMessage = ex.Message;
			if (!string.IsNullOrEmpty(exMessage) && exMessage.IndexOf("UNIQUE") > -1)
				exMessage = "This username (or email) already exists.";

			Message.Text = "A user with the name of " + txtExistingUserName.Text + " could not be updated.<br />" +
								exMessage;
			Message.Type = StatusType.Error;

            Message1.Text = Message.Text;
            Message1.Type = Message.Type;
		}
	}

	protected void CreateUser_Click(object sender, EventArgs e)
	{
		try
		{
			AstroUsers.CreateUser(Server.HtmlEncode(txtUserName.Text.Trim()), txtPassword.Text.Trim(), txtEmail.Text.Trim(), AstroUsers.EveryoneRole);

			Response.Redirect("~/astro-admin/user-management/users/?user=" + txtUserName.Text + "&new=true");

		}
		catch (Exception ex)
		{
			string exMessage = ex.Message;
			if (!string.IsNullOrEmpty(exMessage) && exMessage.IndexOf("UNIQUE") > -1)
				exMessage = "This user (or email) already exists.";

			Message.Text = "A name or email with the name of " + txtUserName.Text + " could not be created.<br />" +
								exMessage;
			Message.Type = StatusType.Error;

            Message1.Text = Message.Text;
            Message1.Type = Message.Type;
		}
	}

	protected bool CanDelete()
	{
		if (AstroUsers.CanDeleteUsers && AstroUsers.IsAdmin(AstroUsers.Current))
			return true;

		return false;
	}

}
